<template>
  <page-dialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-list="dialogInfo.btList"
  >
    <div class="filter-wrapper">
      <NewPageFilter
        v-model:query="filterInfo.query.queryMap"
        :query-more-json="true"
        :filter-list="filterInfo.searchList"
        :filter-btn="filterInfo.searchBtn"
        :clear-type="clearType"
        :slip-select-request="slipSelectRequest"
      >
        <template v-slot:filter-code>
          <div class="scan-input-box">
            <el-input
              ref="codeInput"
              v-focus
              v-model="filterInfo.code"
              :clearable="true"
              style="width: 400px"
              placeholder="请扫码或输入发货单二维码"
              @keyup.enter.native="sacn"
              @input="(e) => (code = validSe(e))"
            >
              <template #prepend>发货单二维码</template>
            </el-input>
          </div>
        </template>
        <template v-slot:filter-receiveAll>
          <el-checkbox
            v-model="receiveAll"
            label="整单收货"
            border
          ></el-checkbox>
        </template>
      </NewPageFilter>
      <div class="display-flex">
        <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
      </div>
    </div>
    <!-- 条件栏 -->
    <DialogTable
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      :api="tableInfo.api"
      :query="filterInfo.query"
      v-model:data="tableInfo.data"
      :field-list="tableInfo.fieldList"
      :handle="tableInfo.handle"
      :highlight-row="highlightRow"
      :check-box="checkBox"
      :isDynamic="false"
      @handleEvent="handleEvent"
    >
      <template v-slot:col-qty="scope">
        {{ $fn.Subtr(scope.row.qty, scope.row.receiveQty || 0) }}
      </template>
    </DialogTable>
  </page-dialog>
  <SetPreference
    v-if="preferenceInfo.visible"
    v-model:visible="preferenceInfo.visible"
    :search-list="filterInfo.searchList"
    :field-list="tableInfo.fieldList"
    :customize-user-v-o="filterInfo.query.customizeUserVO"
    @callback="setPreferenceCallback"
  />
</template>
<script setup name="addBydeliverOrder">
import PageDialog from '@/components/PageDialog/index'
import SetPreference from '@/components/SetPreference/defaultSetPreference'
import { getPendDealDeliverOrderCustomizeListPage } from '@/api/supplier.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { getSupplierAll } from '@/api/core'
import { receivingsScanDeliverCode } from '@/api/stock'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: true,
  },
  checkBox: {
    type: Boolean,
    default: false,
  },
  visible: {
    type: Boolean,
    default: false,
  },
  isEstimated: {
    type: Boolean,
    default: false,
  },
})

const shows = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件shows
  },
})

// 过滤相关配置
const receiveAll = ref(true)
const clearType = ref(true)
const selectRow = ref({})
const slipSelectRequest = ref(true)
const filterInfo = reactive({
  code: '',
  query: {
    sortString: '',
    copyQueryMap: {},
    groupMap: {},
    groups: [],
    queryMap: {},
    defaultQueryMap: {
      deliverProductType: {
        queryType: 'IN',
        value: 1,
      },
      supplierAuth: {
        asTbName: 'deliver_order',
        columnName: 'org_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'supplierAuth',
      },
    },
    queryParams: {},
    customizeUserVO: {},
  },

  searchList: [
    // { slot: true, label: '请扫码', value: 'code' },
    // {
    //   componentType: 'input',
    //   label: '发货单号',
    //   value: 'orderNo',
    //   event: search,
    // },
    // {
    //   componentType: 'input',
    //   label: '采购单号',
    //   value: 'purchNo',
    //   event: search,
    // },
    // {
    //   componentType: 'input',
    //   label: '收货地址',
    //   value: 'receiveAddress',
    //   event: search,
    // },
    // {
    //   componentType: 'select-model',
    //   code: 'default_no_or_yes',
    //   label: '是否暂估入库',
    //   value: 'isEstimationStockBusiness',
    //   show:
    //     proxy.$store.state.permission.systemConfig
    //       .is_estimation_stock_business == 1,
    //   event: search,
    // },
    // {
    //   componentType: 'slip-select',
    //   value: 'supplierIdMult',
    //   label: '供应商',
    //   api: getSupplierAll,
    //   query: { supplierAuth: 'supplierId', sort: 'create_time desc' },
    //   clearable: true,
    //   filterable: true,
    //   keyField: 'supplierName',
    //   valueField: 'supplierId',
    //   event: search,
    // },
  ],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '重置', event: clearSearch },
    { type: 'slot', value: 'receiveAll' },
  ],
})

// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: '',
  fieldList: [
    // { label: '发货单号', value: 'orderNo' },
    // { label: '采购单号', value: 'purchNo' },
    // { label: '收货地址', value: 'receiveAddress' },
    // { label: '供应商', value: 'supplierName' },
    // { label: '状态', value: 'statusValue' },
    // { label: '备注', value: 'remark' },
  ],
})
// 弹窗相关
const dialogInfo = reactive({
  title: '未完成订单',
  width: '80%',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    { label: '保存', event: handleSave, disabled: true, show: true },
  ],
})
const preferenceInfo = ref({
  visible: false,
})

function getList() {
  proxy.$nextTick(() => {
    tableInfo.refresh = Math.random()
  })
}
function search() {
  proxy.$nextTick(() => {
    tableInfo.initCurpage = Math.random()
    tableInfo.refresh = Math.random()
  })
}
function sacn() {
  if (!filterInfo.code) {
    proxy.$message({
      message: '请扫码',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  receivingsScanDeliverCode(encodeURIComponent(filterInfo.code))
    .then((res) => {
      if (res && res.success) {
        shows.value = false
        emit('callback', {
          data: res.data,
          receiveAll: receiveAll.value,
        })
      } else {
        filterInfo.code = ''
      }
    })
    .catch(() => {
      filterInfo.code = ''
    })
}
function handleEvent(event, data) {
  if (event === 'tableClickRow') {
    if (data && data.id) {
      selectRow.value = data
      dialogInfo.btList[1].disabled = false
    }
  }
}
function handleSave() {
  shows.value = false
  emit('callback', {
    data: selectRow.value,
    receiveAll: receiveAll.value,
    isEstimated: props.isEstimated,
  })
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
}
function clearSearch() {
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  clearType.value = !clearType.value
  getList()
}
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
setData()
function setData() {
  let obj = {
    price: {
      label: '单价',
      value: 'price',
      type: 'column',
      componentType: 'price',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('receiving:price'),
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
      componentType: 'price',
      type: 'column',
      permission: !proxy.$permission('receiving:price'),
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      componentType: 'price',
      permission: !proxy.$permission('receiving:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
      show: false,
    },
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'deliver_order_status',
      show: false,
      hidden: true,
    },
    supplierName: {
      label: '供应商',
      value: 'supplierName',
      asValue: 'orgId',
      componentType: 'slip-select',
      api: getSupplierAll,
      query: {
        supplierAuth: 'supplierId',
        sort: 'create_time desc',
      },
      clearable: true,
      filterable: true,
      keyField: 'supplierName',
      valueField: 'supplierId',
      show: false,
      hidden: true,
    },
    orderNo: {
      label: '收货单号',
      value: 'orderNo',
      componentType: 'input',
      show: false,
      hidden: true,
    },
  }
  tableInfo.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
    commonName: {
      label: '通用名称',
      value: 'commonName',
      componentType: 'input',
      show: false,
      hidden: true,
    },
  })
  getCustomize()
}
function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo
  let param = {
    tableKey:
      'stockReceivingByDeliverOrder-com.slip.spd.entity.vo.supplier.DeliverOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail,
        true
      )
      let queryMap = {
        status: {
          queryType: 'IN',
          value: '2,3',
        },
      }
      _tableInfo.fieldList = tableFieldInfo.fieldList
      let searchDefaultValue = searchInfo.searchList.find(
        (item) => item.value === 'statusValue'
      ).searchDefaultValue
      filterInfo.query.queryMap = {
        ...filterInfo.query.defaultQueryMap,
        ...searchInfo.queryMap,
      }
      if (!searchDefaultValue) {
        filterInfo.query.queryMap = {
          ...filterInfo.query.queryMap,
          ...queryMap,
        }
      }
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      if (props.fromType === 'route') {
        filterInfo.query.queryMap = {
          ...filterInfo.query.queryMap,
          ...props.query,
        }
      }
      let searchArr = [
        {
          slot: true,
          label: '请扫码',
          value: 'code',
        },
      ]
      filterInfo.searchList = searchArr.concat(searchInfo.searchList)
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      if (props.isEstimated) {
        filterInfo.query.queryMap['isConsignBusiness'].value = '0'
        filterInfo.searchList.forEach((item) => {
          if (
            item.value === 'isConsignBusinessValue' ||
            item.value === 'isEstimationStockBusinessValue'
          ) {
            item.show = false
          }
        })
      }
      slipSelectRequest.value = _slipSelectRequest
      _tableInfo.api = getPendDealDeliverOrderCustomizeListPage
      getList()
    }
  })
}
</script>
